//
//  JYBaseKeyBoard.swift
//  JYCalculate
//
//  Created by 何治军 on 2018/10/27.
//  Copyright © 2018 何治军. All rights reserved.
//

import UIKit
protocol JYBaseKeyBoardDelegate : NSObjectProtocol {
    func clickKeyBoardBtn(item:String)
}
class JYBaseKeyBoard: UIView {
    
    
    weak var delegate: JYBaseKeyBoardDelegate?

    
    /// 设置键盘按钮文字，但为“”则会隐藏
    var btnTitleArray:[String] = [] {
        didSet{
            addKeyBoardBtn()
        }
    }
    /// 通过btnTitleArray生成的按钮
    var keyBoardBtnArray:[JYBaseKeyBoardButton] = []
    
    /// 用于重新布局
    func setTheConstraints() {
        
    }
    
    convenience init() {
        self.init(frame: CGRect())
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = JYVCGrayBackGroundColor
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override class var requiresConstraintBasedLayout :Bool {
        get{
            return true
        }
    }
    
    override func updateConstraints() {
        super.updateConstraints()
        setTheConstraints()
    }
    
    //MARK - 添加键盘按钮
    fileprivate func addKeyBoardBtn(){
        for btn in keyBoardBtnArray {
            btn .removeFromSuperview()
        }
        keyBoardBtnArray = []
        for title in btnTitleArray {
            let btn = JYBaseKeyBoardButton()
            btn.setTitle(title, for: .normal)
            if title == "AC" {
                btn.setTitleColor(JYDetailRedColor, for: .normal)
            }else if title == "=" {
                btn.setTitleColor(UIColor.white, for: .normal)
                btn.backgroundColor = JYDetailRedColor
            }else if title == "" {
                btn.isHidden = true
            }
            btn.addTarget(self, action: #selector(clickTheBoardButton(_:)), for: .touchUpInside)
            self.addSubview(btn)
            keyBoardBtnArray.append(btn)
        }
    }
    
    @objc fileprivate func clickTheBoardButton(_ btn:JYBaseKeyBoardButton) {
        if let title = btn.title(for: .normal) {
            self.delegate?.clickKeyBoardBtn(item: title)
        }
    }
}

class JYBaseKeyBoardButton: UIButton {
    convenience init() {
        self.init(frame: CGRect())
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setInfo()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setInfo() {
        self.backgroundColor = JYButtonColor
        self.layer.borderColor = JYSeparatorLineColor.cgColor
        self.layer.borderWidth = 0.5
        self.setTitleColor(JYButtonTitleColor, for: .normal)
        self.titleLabel?.font = UIFont.systemFont(ofSize: 22)
    }
}
